package discovery

import (
	"context"
	"time"

	"github.com/libp2p/go-libp2p-core/host"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	"hundsun.com/hsl/hschain/common/log/logging"
	"hundsun.com/hsl/hschain/p2p/common"
	"hundsun.com/hsl/hschain/p2p/common/utils"
)

func initInnerPeers(host host.Host, peersInfo []peer.AddrInfo, cfg *common.P2pConfig, logger logging.Log) {
	var connected = false
reTry:
	for _, node := range cfg.BootstrapPeers {
		info, err := utils.GenAddrInfo(node)
		if err != nil {
			logger.Errorf("wrong config of bootstrap peer:%s, reason:%v", node, err)
			continue
		}
		if info == nil || info.ID == host.ID() {
			continue
		}
		host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.PermanentAddrTTL)
		err = host.Connect(context.Background(), *info)
		if err != nil {
			logger.Errorf("connect with bootstrap peer failed, retry after 10 seconds , reason:%v", err)
			continue
		}
		connected = true
	}
	if !connected && len(cfg.BootstrapPeers) != 0 {
		time.Sleep(time.Duration(10) * time.Second)
		goto reTry
	}

	// 受保护的连接节点,为共识时候预留
	for _, prot := range cfg.ProtectPeers {
		info, err := utils.GenAddrInfo(prot)
		if err != nil {
			logger.Errorf("wrong config of protected peer:%s, reason:%v", prot, err)
			continue
		}
		if info == nil || info.ID == host.ID() {
			continue
		}
		host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.PermanentAddrTTL)
		err = host.Connect(context.Background(), *info)
		if err != nil {
			logger.Error("Host Connect", "err", err, "peer", info.ID)
			continue
		}
		//加保护
		host.ConnManager().Protect(info.ID, "protectNode")
	}

	for _, peerinfo := range peersInfo {
		host.Peerstore().AddAddrs(peerinfo.ID, peerinfo.Addrs, peerstore.TempAddrTTL)
		err := host.Connect(context.Background(), peerinfo)
		if err != nil {
			logger.Error("Host Connect", "err", err)
			continue
		}
	}
}
